/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 选项卡、表格、弹出确认框
import {
  Tabs,
  Form,
  Table,
  Pagination,
  Modal,
  message,
  Input,
  Select,
  Row,
  Col,
  Checkbox,
  Button,
  Icon,
  Radio,
  InputNumber,
  Card,
  Popconfirm,
  Tree
} from 'antd'
// 获取样式类名
import cx from 'classnames'
// 当前页面样式
import styles from './roleModifyStyle.less'
import moment from 'moment'
// import {Grid} from '../../../../components/Grid/Grid'
import { Grid, QueryCondition } from 'widget/Grid/index'
import _ from 'lodash'
// 判断对象是否为空
import { Link, hashHistory } from 'dva/router'
import { listConfig } from '../../../../config/config'

//引入弹出窗控件
// import BoxPopup from '../common/boxPopup/index'
import PopUpSelect from 'widget/PopUpSelect/PopUpSelect'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { mapStateToProps } from 'utils/view_utils'

const FormItem = Form.Item
const TreeNode = Tree.TreeNode
const Option = Select.Option
const ButtonGroup = Button.Group
const TabPane = Tabs.TabPane
// 弹出框表单项布局
const formItemLayout2 = {
  labelCol: {span: 6},
  wrapperCol: {span: 18}
}

const routeView = function ({dispatch, model, form}) {
    const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
    const {modelObj, namespace} = model
    const {
      rowIndex, //过滤序号
      data,
      search,
      userListData,
      userLisDataSelect,
      code,
      name,
      applicationId,
      roleType,
      applicationName,
      resourceAll,
      checkedKeys,
      halfCheckedKeys,
      appListData,
      type,
      isShowDialog,
      saveDisabled,
      roleDetail
    } = modelObj
    // 表单项布局
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 8}
    }
    
    //修改状态
    const changeState = (payload) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {...payload}
      })
    }
    
    const onChangeCode = (e) => {
      changeState({
        stateName: 'code',
        value: e.target.value
      })
    }
    
    const onChangeName = (e) => {
      changeState({
        stateName: 'name',
        value: e.target.value
      })
    }
    
    const onChangeResource = (c, e) => {
      changeState({
        checkedKeys: c,
        halfCheckedKeys: e.halfCheckedKeys
      })
    }
    
    const addOrSaveEdit = () => {
      dispatch({type: `${namespace}/addOrSaveEdit`, payload: {}})
    }
    
    //递归遍历树节点
    const loop = (data) => data.map((item, index) => {
      if (item.child && item.child.length > 0) {
        return (
          <TreeNode key={item.id}
                    title={<div>{item.name}</div>}>
            {loop(item.child)}
          </TreeNode>
        )
      }
      return <TreeNode key={item.id}
                       title={<div>{item.name}</div>}/>
    })


//状态值变化
    function updateModel (value, name, modHierarchy) {
      let obj = modelObj
      if (modHierarchy) {
        /*modHierarchy = modHierarchy.split(".");
        modHierarchy.map(e=> {
          obj = obj[e];
        });*/
        obj[modHierarchy][name] = value
      } else {
        obj[name] = value
      }
      // 分发到model
      dispatch({
        type: `${namespace}/updateStore`,
        payload: obj
      })
    }
    
    let btnListColumns = [
      {title: 'UI资源名称', dataIndex: 'name', key: 'name', width: 100},
      {title: 'UI资源编号', dataIndex: 'code', key: 'code', width: 100},
      {title: 'UI资源说明', dataIndex: 'description', key: 'description',},
      {
        title: '操作', width: 170,
        render: (item) => {
          let list = modelObj.getBtnList || []
          return <div>
            <Select value={String(item.defaultAction)} onChange={(e) => {
              list.map(function (it) {
                if (item.id == it.id) {
                  it.defaultAction = e
                }
              })
              updateModel(list, 'getBtnList')
            }}>
              {
                modelObj.btnOptionList.map((item) => {
                  return <Option key={`modalOption${item.id}`} value={String(item.id)}>{item.text}</Option>
                })
              }
            </Select>
            {
              //如果类型是js脚本， 显示一个输入框
              item.defaultAction == 4 ? <Input style={{height: 60, marginTop: 8}} onChange={(e) => {
                list.map(function (it) {
                  if (item.id == it.id) {
                    it.jsContent = e.target.value
                  }
                })
                updateModel(list, 'getBtnList')
              }} placeholder="请输入js脚本" type="textarea" value={item.jsContent}/> : ''
            }
          </div>
        }
      },
    ]
    
    //筛选出当前资源下的按钮资源
    const modalTableData = () => {
      let id = modelObj.trrOnDate
      let getBtnList = modelObj.getBtnList || []
      let data = []
      getBtnList.map((item) => {
        if (item.parentId == id) {
          data.push(item)
        }
      })
      return data
    }
    
    const modalData = {
      columns: btnListColumns,
      tableData: {total: '', dataSource: modalTableData()},
      pageConfig: {
        current: 1,
        pageSize: 100
      }
    }
    
    // 路由视图
    return (
      <div className={cx('public_listMain', styles.divWrap)}>
        <div className={cx('functionButton', styles.savaBtn)}>
          <span style={{color: '#999'}}>（注：先保存角色信息，再关联资源）</span>
          <Button type='primary' disabled={type == 'edit' && roleDetail.id == undefined} loading={saveDisabled}
                  onClick={addOrSaveEdit}><i className={'iconfont icon-baocun'}/>保 存</Button>
        </div>
        {/*角色信息*/}
        <CollapsiblePanels title='角色信息' style={{marginTop: 16}}>
          <div className={styles.info}>
            {/*新增角色字段*/}
            {
              type == 'edit' ? <Row>
                  <Col {...listConfig.searchCol}>
                    <FormItem {...listConfig.searchFormItem} labelCol={{span: 4}} label={<span>创建人</span>} hasFeedback>
                      <span style={{color: '#999'}}>{roleDetail.createPerson}</span>
                    </FormItem>
                  </Col>
                  <Col {...listConfig.searchCol}>
                    <FormItem {...listConfig.searchFormItem} labelCol={{span: 4}} label={<span>创建时间</span>} hasFeedback>
                      <span style={{color: '#999'}}>{roleDetail.createTime}</span>
                    </FormItem>
                  </Col>
                  <Col {...listConfig.searchCol}>
                    <FormItem {...listConfig.searchFormItem} labelCol={{span: 4}} label={<span>状态</span>} hasFeedback>
                      <span style={{color: '#999'}}>{roleDetail.status == 1 ? '启用' : '禁用'}</span>
                    </FormItem>
                  </Col>
                </Row>
                : ''
            }
            
            <Row>
              <Col {...listConfig.searchCol}>
                <FormItem {...listConfig.searchFormItem} labelCol={{span: 4}}
                          label={<span><span style={{color: '#FFA100'}}>*</span> 角色编号</span>}
                          hasFeedback>
                  <Input placeholder={'请填写角色编号'} onChange={onChangeCode} value={code} maxLength={'20'}/>
                </FormItem>
              </Col>
              <Col {...listConfig.searchCol}>
                <FormItem {...listConfig.searchFormItem} labelCol={{span: 4}}
                          label={<span><span style={{color: '#FFA100'}}>*</span> 角色名称</span>}
                          hasFeedback>
                  <Input placeholder={'请填写角色名称'} onChange={onChangeName} value={name} maxLength={'20'}/>
                </FormItem>
              </Col>
            
            </Row>
          </div>
        </CollapsiblePanels>
        
        {/*应用及资源*/}
        <CollapsiblePanels title='应用及资源' style={{position: 'relative'}}>
          
          <Row className={styles.ziyuanWrap}>
            <Col span={24} className={styles.gridConter}>
              <div style={{width: '400px'}} className={styles.ziyuanLeft}>
                {
                  resourceAll ? <Tree
                      checkable={true}
                      showLine={true}
                      defaultExpandAll={true}
                      // defaultCheckedKeys={['172']}
                      onCheck={onChangeResource}
                      checkedKeys={{checked: checkedKeys, halfChecked: halfCheckedKeys}}
                      onSelect={e => {
                        updateModel(e[0], 'trrOnDate')
                      }}
                    >
                      {loop(resourceAll)}
                    </Tree>
                    : null
                }
              </div>
              {
                modelObj.trrOnDate ? <Tabs tabPosition="buttom" activeKey="1" type="card">
                  <TabPane tab="页面元素" key="1">
                    <Grid nameSpace={`${namespace}`} data={modalData}
                          scroll={{x: 500}}
                          loading={false}
                          isDisplayOrder={true}
                          paginationFlag={false}
                    />
                  </TabPane>
                </Tabs> : ''
              }
            </Col>
          </Row>
        </CollapsiblePanels>
      </div>
    )
  }


// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
